import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Spin } from 'antd';
import ProductComp from './product';
import HoldTrade from './holdTrade';
import CombinatorialAnalysis from './combinatorialAnalysis';
import MarketAnalysis from './marketAnalysis';
import myStyle from './style.less';
import dataConfig from '../dataConfig';
import CloseBtn from '../../../assets/busi/workStation/Barra/closeModal.png';
import BaseInfoForm from './product/baseInfoForm';
import AddTrade from './holdTrade/addTrade';
@connect(({ loading, workStationM }) => ({
  loading,
  workStationM,
}))
export default class BarraStation extends PureComponent {
  state = {
    showOnly: false, //展示一行还是两行
    stateObj: {
      // productState:3, 产品组合状态
      // holdTradeState:3, 持仓交易管理
      // marketState:4,市场分析
      // portfolioOptimization:3 组合分析优化
    },
    productCode: undefined, //产品组合选中的code
    operateType: undefined, //组合新增删除修改 0-增 1-删 2-改
    loadingStatus: undefined, //页面加载 true false
    hideModal: false, //隐藏弹窗
    pageState: '1', //pageState:1-主页面 2-新增产品 3-添加交易
    pageType: '', // 产品页状态，add/edit/view
    productId: '', // 产品页编辑/查看时，产品id
    isBenchmarkFlag: undefined, // 基准类别
    performanceBenchmarkId: undefined, // 基准id
  };
  UNSAFE_componentWillMount() {
    //监听浏览器窗口变化 得到屏幕大小
    window.addEventListener('resize', this.windowChange);
    this.windowChange();
    this.setState({
      loadingStatus: true,
    });
    setTimeout(() => {
      this.queryProductTableList(); //查询产品组合下拉，判断页面状态
    }, 300);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  //窗口变化 确定显示一行单个 还是一行两个
  windowChange = () => {
    let width = document.body?.clientWidth;
    let showOnly = this.state.showOnly;
    this.setState(
      {
        showOnly: width < dataConfig.dividingSize ? true : false,
      },
      () => {
        let stateObj = this.state.stateObj;
        //窗口变化  状态需要改变 11和1  是不一样的意思 必须要转换
        if (showOnly != undefined && showOnly != this.state.showOnly) {
          if (stateObj.productState < 10) {
            if (stateObj.productState < 3) {
              this.setState({
                stateObj: {
                  productState: '15',
                  holdTradeState: '15',
                  portfolioOptimization: '15',
                  marketState: '15',
                },
              });
            } else {
              this.setState({
                stateObj: {
                  productState: '16',
                  holdTradeState: '12',
                  portfolioOptimization: '12',
                  marketState: '16',
                },
              });
            }
          } else {
            if (stateObj.productState == 21) {
              //无权益状态下
              this.setState({
                stateObj: {
                  productState: '21',
                  holdTradeState: undefined,
                  marketState: '21',
                  portfolioOptimization: undefined,
                },
              });
            } else if (['11', '13', '15'].includes(stateObj.productState)) {
              this.setState({
                stateObj: {
                  productState: '2',
                  holdTradeState: '2',
                  portfolioOptimization: '2',
                  marketState: '2',
                },
              });
            } else {
              this.setState({
                stateObj: {
                  productState: '4',
                  holdTradeState: '3',
                  portfolioOptimization: '3',
                  marketState: '3',
                },
              });
            }
          }
        }
      },
    );
  };
  //请求产品组合列表及组合下拉，判断是否有权益类产品和模拟组合
  queryProductTableList() {
    this.props.dispatch({
      type: 'workStationM/queryProductTableList',
      payload: {},
      callback: (data) => {
        this.setState({
          loadingStatus: false,
        });
        this.initModules(data);
      },
    });
  }
  /**
	 * （1）无权益类产品和模拟组合，各模块状态赋值如下：
		产品组合：state=21 展示对应的缺省页
		持仓交易管理：不加载该模块
		组合分析优化：不加载该模块
		市场分析：state=21展示对应的缺省页
		（2）有权益类产品或模拟组合，将接口获取的列表数据作为入参传入产品组合组件，各模块状态赋值如下
		产品组合：<1920，state=4； >=1920，state=16
		持仓交易管理：<1920，state=3； >=1920，state=12
		组合分析优化：<1920，state=3； >=1920，state=12
		市场分析：<1920，state=4； >=1920，state=16
		* */

  //页面初始化
  initModules = (data) => {
    if (data?.length) {
      // 有权益类产品或模拟组合，各模块状态赋值
      //console.log(this.state.showOnly)
      this.setState({
        stateObj: {
          productState: this.state.showOnly ? '4' : '16',
          holdTradeState: this.state.showOnly ? '3' : '12',
          portfolioOptimization: this.state.showOnly ? '3' : '12',
          marketState: this.state.showOnly ? '4' : '16',
        },
      });
    } else {
      // 无权益类产品和模拟组合，各模块状态赋值
      this.setState({
        stateObj: {
          productState: '21',
          holdTradeState: undefined,
          marketState: '21',
          portfolioOptimization: undefined,
        },
      });
    }
  };
  componentWillUnmount() {
    // 删除窗口大小的监听
    window.removeEventListener('resize', this.windowChange);
  }
  /**
	 * 拆分成四个大组件：产品组合、持仓交易管理、市场分析、组合分析优化，每个组件有以下几个状态，组件应该是什么状态，应该是框架分析后，向组件内部传入状态。
	state=1：<1920 折叠 选择了组合
	state=2：<1920 展开 选择了组合
	state=3：<1920 折叠 未选择组合
	state=4：<1920 展开 未选择组合
	state=11：>=1920 单折叠 选择了组合
	state=12：>=1920 单折叠 未选择组合
	state=13：>=1920 双折叠 选择了组合
	state=14：>=1920 双折叠 未选择组合
	state=15：>=1920 展开 选择了组合
	state=16：>=1920 展开 未选择组合
	state=21：无权益类产品和模拟组合
	框架上根据每个组件的状态，根据各自的情况，单独给更新状态的组件传参；
	在state里建一个变量存储各自的状态，stateObj:{产品组合productState:3, 持仓交易管理holdTradeState:3, 市场分析marketState:4, 组合分析优化portfolioOptimization:3}
	*/
  //1920改变展开折叠状态
  changeState = (type, type1, fromOperate) => {
    let stateObj = this.state.stateObj;
    let leftStatus = stateObj[type];
    let rightStatus = stateObj[type1];
    console.log(leftStatus, rightStatus);
    if (fromOperate) {
      //来自增删改 引起的页面状态改变
      let productState = stateObj['productState'];
      if (productState == '16') {
        this.initModules(this.props.workStationM.productTableList);
      }
      return;
    }
    // 右侧单折叠
    if (leftStatus == '15' && rightStatus == '11') {
      leftStatus = '13';
      rightStatus = '13';
      console.log('***1**');
    } else if (leftStatus == '16' && rightStatus == '12') {
      leftStatus = '14';
      rightStatus = '14';
      console.log('***2**');
    }
    //右侧展开
    else if (leftStatus == '15' && rightStatus == '15') {
      leftStatus = '11';
      rightStatus = '15';
      console.log('***3**');
    } else if (leftStatus == '16' && rightStatus == '16') {
      leftStatus = '12';
      rightStatus = '16';
      console.log('***4**');
    } else if (leftStatus == '13' && rightStatus == '13') {
      //双折叠选择组合
      leftStatus = '15';
      rightStatus = '11';
      console.log('***5**');
    } else if (leftStatus == '14' && rightStatus == '14') {
      //双折叠未选择组合
      leftStatus = '16';
      rightStatus = '12'; //少一个都展开的状态
      console.log('***6**');
    } else if (leftStatus == '11' && rightStatus == '15') {
      //左侧单折叠 右侧展开
      leftStatus = '15';
      rightStatus = '15';
      console.log('***7**');
    } else if (leftStatus == '12' && rightStatus == '16') {
      leftStatus = '16';
      rightStatus = '16';
      console.log('***8**');
    }
    stateObj[type] = leftStatus;
    stateObj[type1] = rightStatus;
    this.setState({
      stateObj: { ...stateObj },
    });
  };
  //小于1920 展开折叠状态改变
  onlyChangeStatus = (e, type, fromOperate) => {
    let stateObj = this.state.stateObj;
    if (fromOperate) {
      //来自增删改 引起的页面状态改变
      let productState = stateObj['productState'];
      if (productState == '4') {
        this.initModules(this.props.workStationM.productTableList);
      }
      return;
    }
    let data = stateObj[type];
    if (data == 1) {
      data = '2';
    } else if (data == 2) {
      data = '1';
    } else if (data == 3) {
      data = '4';
    } else if (data == 4) {
      data = '3';
    }
    stateObj[type] = data;
    this.setState({
      stateObj: { ...stateObj },
    });
  };
  //组合新增 修改 删除 变更的组合code，0-增 1-删 2-改;
  productOnChange = (code, operateType) => {
    const { productState, holdTradeState, marketState, portfolioOptimization } = this.state.stateObj;
    const stateObj = this.state.stateObj;
    let productCode = this.state.productCode;
    console.log(code, operateType, '拿到子组件给的code和状态');
    if (operateType != undefined) {
      //有operateType 则是增删改 得到的组合code和操作
      if (code == productCode && operateType == 1) {
        //删除的 正好是选中的；则产品组合的状态变更为 展开未选择组合
        stateObj['productState'] = productState == '2' ? '4' : '16';
        this.setState({
          productCode: undefined,
          stateObj: {
            ...stateObj,
          },
        });
      }
      if (this.props.workStationM.productTableList.length == 1 && operateType == 1) {
        //如产品组合删除光了，则
        this.initModules([]);
        return;
      }
      if (operateType == 0 && productState == '21') {
        //产品组合无数据状态下新增之后 更新状态
        this.initModules([1]);
        return;
      }
      this.HoldTradeRef?.productOnChange(code, operateType); //增删改 给到组件内部自行判断

      return;
    } else {
      //没有operateType 则是双击组合得到的组合code
      this.setState({
        productCode: code,
      });
    }

    //原先是未选中组合 则需要变更状态为选中组合的状态
    if (productCode == undefined) {
      console.log('***未选中组合 变为选中**');
      this.setState({
        stateObj: {
          productState: this.formatData(productState),
          holdTradeState: this.formatData(holdTradeState),
          marketState: this.formatData(marketState),
          portfolioOptimization: this.formatData(portfolioOptimization),
        },
      });
    }
  };
  formatData = (val) => {
    let temp;
    if (val == '3') {
      temp = '2';
    } else if (val == '4') {
      temp = '2';
    } else if (val == '12') {
      temp = '15';
    } else if (val == '14') {
      temp = '16';
    } else if (val == '16') {
      temp = '15';
    }
    return temp;
  };
  //关闭欢迎使用的弹窗
  closeModal = () => {
    this.setState({
      hideModal: true,
    });
  };
  //新增产品成功 通知产品组件刷新 并回到主页
  addNewProduct = () => {
    this.setState({
      pageState: 1,
    });
    this.state.myProductRef?.refresh();
  };
  //改变是否显示主页面
  changePage = (e, type) => {
    this.setState({
      pageState: e,
    });
    if (type) {
      this.setState({
        mode: type, //是什么模式 指令还是簿记
      });
    }
  };

  // 产品编辑/详情时
  jumpProductPage = (type, productId) => {
    this.setState({
      pageType: type,
      productId: productId,
    });
  };

  //添加交易成功 通知交易刷新列表
  addStock = () => {
    this.setState({
      pageState: 1,
    });
    this.HoldTradeRef?.refreshHoldTrade();
  };
  //真实还是模拟产品
  changePortfolio = (record) => {
    this.setState({
      portfolioType: record.portfolioType,
      isBenchmarkFlag: record.isBenchmarkFlag,
      performanceBenchmarkId: record.performanceBenchmarkId,
    });
  };
  render() {
    const { portfolioType, showOnly, productCode, loadingStatus, hideModal, pageState, pageType, productId, isBenchmarkFlag, performanceBenchmarkId } = this.state;
    const { productTableList } = this.props.workStationM;
    const { productState, holdTradeState, marketState, portfolioOptimization } = this.state.stateObj;
    let formatStyle = (data0, data1) => {
      let width;
      if ((data0 == 16 && data1 == 12) || (data0 == 15 && data1 == 11)) {
        //左侧展开 右侧收缩
        width = `calc(100% - ${dataConfig.shrinkSize.width} - 24px)`;
      } else if (data0 == 11 || data0 == 12) {
        //左侧单折叠
        width = dataConfig.shrinkSize.width;
      } else if (data0 == 21 && !holdTradeState) {
        width = '100%';
      } else {
        //自适应
        width = undefined;
      }
      return width;
    };
    let formatHeight = (data, data0, type) => {
      let height;
      height = ['1', '3'].includes(data) ? dataConfig.shrinkSize.height : ['2', '4'].includes(data) ? 'auto' : type ? (['11', '12'].includes(data) ? '570px' : 'auto') : '570px';
      if ((data == 13 && data0 == 13) || (data == 14 && data0 == 14)) {
        //双折叠高度
        height = dataConfig.shrinkSize.height;
      }
      return height;
    };

    return (
      <div
        style={loadingStatus ? { height: '300px' } : {}}
        className={
          loadingStatus
            ? ''
            : pageState == 1
            ? showOnly
              ? `${myStyle.barraStation} ${myStyle.showOnly}`
              : `${myStyle.barraStation}  ${myStyle.showMore}`
            : `${myStyle.barraStation} `
        }
      >
        {loadingStatus ? (
          <Spin spinning={loadingStatus} style={{ height: 'calc(100vh - 54px', width: '100%', border: '0' }}>
            <div style={{ border: '0' }}></div>
          </Spin>
        ) : (
          <>
            <div style={{ display: pageState == 1 ? 'flex' : 'none' }}>
              <div
                style={{
                  height: formatHeight(productState, holdTradeState),
                  width: formatStyle(productState, holdTradeState),
                  minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                }}
              >
                {productTableList?.length && !productCode && !hideModal ? (
                  <div className={myStyle.myModal}>
                    <p>欢迎使用Barra</p>
                    <p>请选择产品/组合，开始使用</p>
                    <img src={CloseBtn} onClick={this.closeModal} />
                  </div>
                ) : null}
                <ProductComp
                  state={productState}
                  stateOnChange={(e) => {
                    showOnly ? this.onlyChangeStatus(e, 'productState') : this.changeState('productState', 'holdTradeState');
                  }}
                  productOnChange={this.productOnChange}
                  selectedOnChange={this.productOnChange}
                  onRef={(ref) => (this.state.myProductRef = ref)}
                  changePage={this.changePage}
                  jumpProductPage={this.jumpProductPage}
                  changePortfolio={this.changePortfolio}
                  benchmarkOnChange={this.benchmarkOnChange}
                />
              </div>
              {holdTradeState && (
                <div
                  style={{
                    height: formatHeight(holdTradeState, productState),
                    width: formatStyle(holdTradeState, productState),
                    minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                  }}
                >
                  <HoldTrade
                    showOnly={showOnly}
                    state={holdTradeState}
                    productCode={productCode}
                    stateOnChange={(e, type) => {
                      showOnly ? this.onlyChangeStatus(e, 'holdTradeState', type) : this.changeState('holdTradeState', 'productState', type);
                    }}
                    onRef={(ref) => (this.HoldTradeRef = ref)}
                    changePage={this.changePage}
                  />
                </div>
              )}
              <div
                style={{
                  height: formatHeight(marketState, portfolioOptimization, 'bottom'),
                  width: formatStyle(marketState, portfolioOptimization),
                  minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                }}
              >
                <MarketAnalysis
                  state={marketState}
                  productCode={productCode}
                  stateOnChange={(e) => {
                    showOnly ? this.onlyChangeStatus(e, 'marketState') : this.changeState('marketState', 'portfolioOptimization');
                  }}
                  style={{ minWidth: showOnly ? dataConfig.compMinWidth : 'auto' }}
                />
              </div>

              {portfolioOptimization && (
                <div
                  id='myPortAnalysis'
                  style={{
                    height: formatHeight(portfolioOptimization, marketState, 'bottom'),
                    width: formatStyle(portfolioOptimization, marketState),
                    minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                  }}
                >
                  <CombinatorialAnalysis
                    portfolioType={portfolioType}
                    state={portfolioOptimization}
                    onRef={(ref) => (this.CombinatorialAnalysisRef = ref)}
                    productCode={productCode}
                    stateOnChange={(e) => {
                      showOnly ? this.onlyChangeStatus(e, 'portfolioOptimization') : this.changeState('portfolioOptimization', 'marketState');
                    }}
                    operateType={this.state.operateType}
                    style={{ minWidth: showOnly ? dataConfig.compMinWidth : 'auto' }}
                    flag={isBenchmarkFlag}
                    indexCode={performanceBenchmarkId}
                  />
                </div>
              )}
            </div>
            {pageState > 1 && (
              <div style={{ background: '#fff' }}>
                {pageState == '2' && <BaseInfoForm addNewProduct={this.addNewProduct} changePage={this.changePage} pageType={pageType} productId={productId} />}
                {pageState == '3' && <AddTrade addStock={this.addStock} changePage={this.changePage} mode={this.state.mode} />}
              </div>
            )}
          </>
        )}
      </div>
    );
  }
}
